package com.mes.web.controller.tdd;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mes.entity.hpf.SaleOutDetail;
import com.mes.entity.hpf.SaleReturnDetail;
import com.mes.entity.jy.Tempproduct;
import com.mes.entity.lc.ProductGoku;
import com.mes.entity.lc.ProductReturn;
import com.mes.entity.lc.ProductStock;
import com.mes.entity.tdd.ProductRmoveDetail;
import com.mes.entity.tdd.tj.ProductOut;
import com.mes.entity.yzlExtend.ExtendOutlib;
import com.mes.entity.yzlExtend.ExtendProductor;
import com.mes.entity.yzlExtend.ExtendReturnOdrer;
import com.mes.service.tdd.ArpsService;
import com.mes.service.yzl.OutlibService;
import com.mes.service.yzl.ReturnService;
import com.mes.utils.ResponseUtil;
import com.mes.utils.StringUtil;
/**
 * ARP产品出库，退货，移库
 * @ClassName:ArpsController
 * @Description:
 * @Author tdd
 * @Date 2018年4月12日下午2:58:38
 * @version 1.0
 */
@Controller
@RequestMapping("/arp")
public class ArpsController {
	@Resource
	public ArpsService arpsService;
	@Resource
    OutlibService outlibService;
	@Resource
    ReturnService returnService;
    
	/**
	 * 根据条形码查产品id
	 * @param code 条形码
	 * @param response response对象 
	 * @throws Exception 异常
	 */
	@RequestMapping("/findByCode")
	public void findByCode(String code,HttpServletResponse response) throws Exception{
		/**
    	 * 根据条形码查库存
    	 */
    	ProductStock productStock = new ProductStock();
    	//赋值条码
    	productStock.setRemark2(code);
    	List<ProductStock> productStocks = arpsService.productStockAll(productStock);
    	String tshi = "";
    	Long Productid = null;
    	if(productStocks.size()>0){
    		Productid = productStocks.get(0).getProductidd();
    		//code2 = productStocks.get(0).getRemark2();
    		tshi= "查询成功";
    	}else {
    		//code2 = 0+"";
    		Productid = 0L;
    		tshi = "没有找到该条形码的产品";
    	}
		
    	//获得数据
		response.setContentType("application/json; charset=utf-8"); 
		net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
		//传递数据到页面
		jsonObject.put("code", "200");
		jsonObject.put("message", tshi);
		jsonObject.put("results", Productid);
		ResponseUtil.write(response, jsonObject);
	} 
	/**
	 * 根据条形码查产品id
	 * @param code 条形码
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/findByCodeFor")
	public void findByCodeFor(String code,HttpServletResponse response) throws Exception{
		/**
		 * 根据条形码查库存
		 */
		ProductGoku productGoku = new ProductGoku();
		//赋值条码
		productGoku.setLpcode(code);
		List<ProductGoku> productGokus = arpsService.findByLpcode(productGoku);
		String tshi = "";
		Long Productid = null;
		if(productGokus.size()>0){
			Productid = productGokus.get(0).getPid();
			tshi= "查询成功";
		}else {
			Productid = 0L;
			tshi = "没有找到该条形码的产品";
		}
		
		//获得数据
		response.setContentType("application/json; charset=utf-8"); 
		net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
		//传递数据到页面
		jsonObject.put("code", "200");
		jsonObject.put("message", tshi);
		jsonObject.put("results", Productid);
		ResponseUtil.write(response, jsonObject);
	} 
	/**
	 * 根据条形码查线边库产品id
	 * @param code 条形码
	 * @param response response
	 * @throws Exception 异常
	 */
	@RequestMapping("/findByCodeXb")
	public void findByCodeXb(String code,HttpServletResponse response) throws Exception{
		//获得数据
		response.setContentType("application/json; charset=utf-8"); 
		net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
		/**
		 * 根据条形码查库存
		 */
		Tempproduct tempproduct = new Tempproduct();
		//赋值条码
		tempproduct.setRemark1(code);
		
		List<Tempproduct> tempproducts = arpsService.allTempproduct(tempproduct);
		if(tempproducts.size()>0){
			Tempproduct tempproduct2 = tempproducts.get(0);
			//传递数据到页面
			jsonObject.put("code", "200");
			jsonObject.put("message", "");
			jsonObject.put("results", tempproduct2);
		}else{
			//传递数据到页面
			jsonObject.put("code", "200");
			jsonObject.put("message", "没有找到该条形码的产品");
			jsonObject.put("results", null);
		}
		
		ResponseUtil.write(response, jsonObject);
	} 
	
	
	/**
	 * 查询所有审批通过但未出库的销售出库单
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/outLibOrderList")
	@ResponseBody
	public Map<String, Object> oderlist(HttpServletResponse response) throws Exception {
		ExtendOutlib extendOutlib = new ExtendOutlib();
		//未出库
		extendOutlib.setOutStatus("0");
		//审批通过
		extendOutlib.setSpStatus("2");
        //条件分页查询
        List<ExtendOutlib> list = arpsService.allOutlibList(extendOutlib);
        //获得数据
  		/*response.setContentType("application/json; charset=utf-8"); 
  		net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();*/
  		
  		Map<String, Object> map = new  HashMap<String, Object>();
  		
  		
		//传递数据到页面
  		map.put("code", "200");
  		map.put("message", "");
  		map.put("results", list);
		
  		//ResponseUtil.write(response, map);
		return map;
	}
	/**
	 * 根据销售出库单id查详情
	 * @param id  销售出库单id
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/outOrderXq")
	public void oderlist(Long id,HttpServletResponse response) throws Exception {
        //List<ExtendProductor> list = outlibService.outOrderXq(id);
        int a = 1;
        List<SaleOutDetail> list = new ArrayList<>();
        
        list = outlibService.outDetail(id);
        
        for (SaleOutDetail saleOutDetail : list) {
        	int outQ = saleOutDetail.getOutQ();
        	//包装规格
        	int getrLastPlanQ = saleOutDetail.getrLastPlanQ();
        	int c = outQ / getrLastPlanQ;
        	 
        	int d = outQ % getrLastPlanQ;
        	
        	if(d > 0 ) {
        		//条码数量
        		saleOutDetail.setTnum(c+a);
        	}else {
        		saleOutDetail.setTnum(c);
        	}
		}
        
		//获得数据
		response.setContentType("application/json; charset=utf-8"); 
		net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
			//传递数据到页面
			jsonObject.put("code", "200");
			jsonObject.put("message", "");
			jsonObject.put("results", list);
		ResponseUtil.write(response, jsonObject);
	}
	

    /**
     *  出库处理
     * @param extendProductorList 出库单详情
     * @param response response对象
     * @throws Exception 异常
     */
     
    @RequestMapping("/libOutbound")
    public void libOutbound(String extendProductorList,HttpServletResponse response) throws Exception {
        //转码
    	Gson gson = new Gson();
        List<ProductOut> productOuts = gson.fromJson(extendProductorList, new TypeToken<List<ProductOut>>(){}.getType());

        Long userId = productOuts.get(0).getUserId();
        Long outSaleId = productOuts.get(0).getOutSaleId();
    	
    	//出参信息
    	response.setContentType("application/json; charset=utf-8"); 
		net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
		
		
    	//根据出库单id查审批通过但未出库的出库单
    	ExtendOutlib outlib = new ExtendOutlib();
    	outlib.setId(outSaleId);
    	//未出库
    	outlib.setOutStatus("0");
    	//审批通过
    	outlib.setSpStatus("2");
    	List<ExtendOutlib> allOutlibList = arpsService.allOutlibList(outlib);
    	
    	//根据出库单id查出出库单
    	if (allOutlibList.size() > 0) {
    		//给出库单赋值
			outlib = allOutlibList.get(0);
			
	        
	        /**
	         * 当前时间
	         */
	        SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
	        String   date   =   sDateFormat.format(new Date());
	       
	        //出库单编号
	        String outNumber = outlib.getOutNumber();
	        
	        //客户
	        String name = outlib.getName();
	        
	        //出库记录集合
    		List<ProductGoku> gokus = new ArrayList<>();
    		
    		//是否有库存
    		int iskc = 0;
    		
	        /**
	         * 获取条形码和批次号等
	         * 
	         * 
	         */
	        //遍历出库单详情
	        for (ProductOut productOut : productOuts) {
	        	
	        	//条形码
            	String key = productOut.getProductOutLine();
            	//数量
            	String value = String.valueOf(productOut.getProductOutNum());
            	//打印条形码+数量
            	System.out.println(key + ":" + value);
            	
            	/**
            	 * 根据条形码查库存
            	 */
            	ProductStock productStock = new ProductStock();
            	//赋值条码
            	productStock.setRemark2(key);
            	List<ProductStock> productStocks = arpsService.productStockAll(productStock);
            	
            	//根据条形码查出库存
            	if(productStocks.size()>0){
	            	productStock = productStocks.get(0);
	            	//库存量
	            	String num = productStock.getNum();
	            	
	            	/**
	            	 * 判断库存是否大于出库数量
	            	 */
	            	if(StringUtil.isStr2Num(num) && StringUtil.isStr2Num(value)){
	            		//库存大于出库数量
	            		if(Integer.parseInt(num) >= Integer.parseInt(value)){
		            		
		            		//出库记录
		            		ProductGoku goku = new ProductGoku();
		            		/*产品id*/
		            		goku.setPid(productOut.getProductid());;
		            		// 批次 
		            		goku.setLppici(productStock.getRemark1());;
		            	    // 数量
		            		goku.setLpnum(value);
		            	    // 条形码 
		            		goku.setLpcode(key);;
		            		// 出库单号
		    				goku.setLpodd(outNumber);
		    				//客户
		    				goku.setLpcustome(name);
		    			    // 出库时间 
		    				goku.setLpgotime(date);
		    				// 添加出库记录到集合 
		    				gokus.add(goku);
		    			
		    			//判断库存是否小于出库数量
		            	}else{
		            		iskc=1;
		            		break;//跳出for循环 
		            	}
	            	}
	            	
	            //根据条形码没有查出库存
            	}else{
            		iskc =1;
            		break;//跳出for循环
            	}
	        	
			}
	        
	        
	        if(iskc == 0){
	        	for (ProductGoku goku : gokus) {
	        		//添加出库记录返回id（Long）
	        		arpsService.addProductGoku(goku);
	        	}
	        	
	        	/**
				 * 修改出库单为已出库
				 */
				//销售出库单id
		    	List<Integer> list = new ArrayList<>();
		    	list.add((int) outlib.getId());
		        //销售计划单id
		    	//修改出库单为已出库返回修改条数（int）
		    	outlibService.libOutbound(list);
		    	
		    	/**
		    	 * 修改对应销售计划单为已出库
		    	 */
		        List<Integer> list1 = new ArrayList<>();
		        
		        //获取该出库单对应的计划单id
		        list1.add(productOuts.get(0).getCustomerOrderId());
		        
		        
		        //修改销售计划单为已出库返回修改条数（int）
		        outlibService.cusOrderbound(list1);
		        
		      //传递数据到ARP
				jsonObject.put("code", "200");
				jsonObject.put("message", "出库成功");
				jsonObject.put("results", null);
		       
	        }else{
	        	//传递数据到ARP
				jsonObject.put("code", "200");
				jsonObject.put("message", "库存不足，出库失败");
				jsonObject.put("results", null);
	        }
	        
			
			
    	}else{
 			//传递数据到ARP
 			jsonObject.put("code", "200");
 			jsonObject.put("message", "该出库单已经出库");
 			jsonObject.put("results", null);
 			
    	}
    	ResponseUtil.write(response, jsonObject);
    }
	
	
	
	/**
	 * 所有审批通过未退货的退货单
	 * @param response response对象
	 * @throws Exception 异常
	 */
    @RequestMapping("/returnList")
    @ResponseBody
    public Map<String, Object> returnList(HttpServletResponse response) throws Exception{
    	ExtendReturnOdrer extendReturnOdrer = new ExtendReturnOdrer();
    	//未退货
    	extendReturnOdrer.setReturnsStatus("0");
    	//审批通过
    	extendReturnOdrer.setReturnsExamineStatus("2");
        List<ExtendReturnOdrer> list = arpsService.allReturnOrder(extendReturnOdrer);
        //获得数据
  		/*response.setContentType("application/json; charset=utf-8"); 
  		net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();*/
  		
  		
  		Map<String, Object> map = new  HashMap<String, Object>();
  		
		//传递数据到页面
  		map.put("code", "200");
  		map.put("message", "");
  		map.put("results", list);
		
		
		
  		//ResponseUtil.write(response, map);
		return map;
    }
    /**
     * 根据销售退货单id查详情
     * @param id 销售退货单id
     * @param response response对象
     * @throws Exception 异常
     */
    @RequestMapping("/returnXq")
    public void returnXq(Long id,HttpServletResponse response) throws Exception{
        //List<ExtendProductor> list = returnService.returnOrderXq(id);
    	
    	 List<SaleReturnDetail> list = new ArrayList<>();
         list = returnService.returnDetail(id);
    	
    	//获得数据
    	response.setContentType("application/json; charset=utf-8"); 
    	net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
    		//传递数据到页面
    		jsonObject.put("code", "200");
    		jsonObject.put("message", "");
    		jsonObject.put("results", list);
    	ResponseUtil.write(response, jsonObject);
    }
  
    /**
     * 退货处理
     * @param extendProductorList 退货单详情
     * @param response response对象
     * @throws Exception 异常
     */
	@RequestMapping("/returnProcess")
	public void returnProcess(String extendProductorList,
			HttpServletResponse response) throws Exception {
		/*
		 * //转码 Gson gson = new Gson(); List<ExtendProductor> extendProductors =
		 * gson.fromJson(extendProductorList, new
		 * TypeToken<List<ExtendProductor>>(){}.getType());
		 */// 转码
		Gson gson = new Gson();
		List<ProductOut> productOuts = gson.fromJson(extendProductorList,
				new TypeToken<List<ProductOut>>() {
				}.getType());

		Long userId = productOuts.get(0).getUserId();
		Long returnSaleId = productOuts.get(0).getOutSaleId();

		// 出参信息
		response.setContentType("application/json; charset=utf-8");
		net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();

		// 根据id查审批通过未退货的退货单
		ExtendReturnOdrer extendReturnOdrer = new ExtendReturnOdrer();
		extendReturnOdrer.setId(returnSaleId);
		// 未退货
		extendReturnOdrer.setReturnsStatus("0");
		// 审批通过
		extendReturnOdrer.setReturnsExamineStatus("2");
		List<ExtendReturnOdrer> allReturnOrder = arpsService
				.allReturnOrder(extendReturnOdrer);

		// 根据id查到审批通过未退货的退货单
		if (allReturnOrder.size() > 0) {
			extendReturnOdrer = allReturnOrder.get(0);

			/**
			 * 当前时间
			 */
			SimpleDateFormat sDateFormat = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String date = sDateFormat.format(new Date());

			// 出库单编号
			String outNumber = extendReturnOdrer.getReturnsNumber();
			// 客户
			String name = extendReturnOdrer.getName();

			/**
			 * 获取条形码和批次号等
			 */
			// 遍历出库单详情
			/* for (ExtendProductor extendProductor : extendProductors) */{
				for (ProductOut productOut : productOuts) {

					// 条形码
					String key = productOut.getProductOutLine();
					// 数量
					String value = String
							.valueOf(productOut.getProductOutNum());
					// 打印条形码+数量
					System.out.println(key + ":" + value);

					/**
					 * 根据条形码查出库记录
					 */

					ProductGoku productGoku = new ProductGoku();
					// 赋值条码
					productGoku.setLpcode(key);
					List<ProductGoku> productGokus = arpsService
							.findByLpcode(productGoku);

					// 根据条形码查出出库记录
					if (productGokus.size() > 0) {
						productGoku = productGokus.get(0);

						// 退货记录
						ProductReturn productReturn = new ProductReturn();
						// 产品id
						productReturn.setRematid(productOut.getProductid());
						;
						// 批次
						productReturn.setRepici(productGoku.getLppici());
						;
						// 数量
						productReturn.setRenum(1+"");
						;
						// 条形码
						productReturn.setRecodee(key);
						;
						// 退货单号
						productReturn.setReodd(outNumber);
						;
						// 退货日期
						productReturn.setRetime(date);
						;
						// 客户
						productReturn.setRecustom(name);
						// 添加退货记录返回id
						arpsService.addProductReturn(productReturn);

						// 根据条形码没有查出出库记录
					}

				}
			}

			// 修改退货状态
			List<Integer> list = new ArrayList<>();

			list.add((int) extendReturnOdrer.getId());

			// 修改退货状态返回影响行数
			returnService.returnsProcess(list);

			// 传递数据到页面
			jsonObject.put("code", "200");
			jsonObject.put("message", "销售退货成功");
			jsonObject.put("results", null);

		} else {
			// 传递数据到ARP
			jsonObject.put("code", "200");
			jsonObject.put("message", "该退货单已经退货");
			jsonObject.put("results", null);
		}

		ResponseUtil.write(response, jsonObject);
	}
    
    
    /**
     * 移库处理
     * @param productRmoveDetail 线边库产品库存实体集合
     * @param userId 用户id
     * @param response response对象
     * @throws Exception 异常
     */
    @RequestMapping("/yikuProcess")
    public void yikuProcess(String productRmoveDetail,String userId,HttpServletResponse response) throws Exception{
/*    	JSONObject jsonObjectp = JSONObject.fromObject(productRmoveDetail);
    	ProductRmoveDetail rmoveDetail = (ProductRmoveDetail) JSONObject.toBean(jsonObjectp, ProductRmoveDetail.class);
    	
*/    	response.setContentType("application/json; charset=utf-8"); 
    	net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
    	//当前时间
    	SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
    	String   date   =   sDateFormat.format(new Date());
    	
    	
    	//转码
    	Gson gson = new Gson();
    	List<Tempproduct> tempproducts = gson.fromJson(productRmoveDetail, new TypeToken<List<Tempproduct>>(){}.getType());
    	for (Tempproduct tempproduct : tempproducts) {
    		ProductRmoveDetail rmoveDetail = new ProductRmoveDetail();
    		rmoveDetail.setProductid(Long.valueOf(tempproduct.getPid()));
    		rmoveDetail.setNum(tempproduct.getRemark2());
    		rmoveDetail.setUnit(tempproduct.getRemark5());
    		rmoveDetail.setCode(tempproduct.getRemark1());
    		rmoveDetail.setPici(tempproduct.getRemark());
    		rmoveDetail.setDate(date);
    		rmoveDetail.setPmman(userId);
    		arpsService.addProductRmove(rmoveDetail);
		}
    	
    	
    	
    	/*
    	List<ProductRmoveDetail> rmoveDetails = gson.fromJson(productRmoveDetail, new TypeToken<List<ProductRmoveDetail>>(){}.getType());
    	for (ProductRmoveDetail rmoveDetail : rmoveDetails) {
    		rmoveDetail.setDate(date);
    		//添加移库记录返回id
    		arpsService.addProductRmove(rmoveDetail);
		}
    	*/
    	
    
    	
    	//传递数据到页面
    	jsonObject.put("code", "200");
    	jsonObject.put("message", "产品移库成功");
    	jsonObject.put("results", null);
    	
    	ResponseUtil.write(response, jsonObject);
    }
    
}
